package cn.bob.org.service.impl;

import cn.bob.basic.service.impl.BaseServiceImpl;
import cn.bob.basic.utils.PageList;
import cn.bob.org.domain.Department;
import cn.bob.org.domain.Employee;
import cn.bob.org.mapper.DepartmentMapper;
import cn.bob.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bob
 * @data 2022/9/28-10:55
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        List<Department> deptAll = departmentMapper.findAll();
        List<Department>  depts= new ArrayList<>();
        //使用strem流简化双重for循环
        Map<Long, Department> collect = deptAll.stream().collect(Collectors.toMap(Department::getId, e -> e));
        for (Department department : deptAll) {
            if (null == department.getParentId()){
                depts.add(department);
            }else {
                //找到上级
                Department depart = collect.get(department.getParentId());
                if (depart!=null){
                 depart.getChildren().add(department);
                }
            }
        }
        return depts;
    }
}
